from django import forms
from core.models.school_schedule import SchoolSchedule

class SchoolScheduleForm(forms.ModelForm):
    class Meta:
        model = SchoolSchedule
        fields = ['date', 'is_class_day']
        widgets = {
            'date': forms.DateInput(
                attrs={'type': 'date', 'class': 'form-control'},
                format='%Y-%m-%d'
            ),
            'is_class_day': forms.Select(
                choices=SchoolSchedule.IS_CLASS_DAY_CHOICES,
                attrs={'class': 'form-select'}
            )
        }
        labels = {
            'date': '日期',
            'is_class_day': '是否上课'
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 设置日期字段的初始值为今天
        if not self.instance.pk:
            from django.utils import timezone
            self.fields['date'].initial = timezone.now().date()

    def clean_date(self):
        date = self.cleaned_data.get('date')
        if date and date < timezone.now().date():
            raise forms.ValidationError('不能选择过去的日期')
        return date

    def clean_is_class_day(self):
        is_class_day = self.cleaned_data.get('is_class_day')
        if is_class_day is None:
            raise forms.ValidationError('请选择是否上课')
        # 确保返回整数类型
        try:
            return int(is_class_day)
        except (ValueError, TypeError):
            raise forms.ValidationError('无效的状态值')